<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * This is a sample module for PyroCMS
 *
 * @author 		Jerel Unruh - PyroCMS Dev Team
 * @website		http://unruhdesigns.com
 * @package 	PyroCMS
 * @subpackage 	Sample Module
 */
class Tournament_m extends MY_Model {

	public function __construct()
	{
		parent::__construct();
		$this->load->library('module_helper');
	}

	function tournament_submit(){
		$show_tournament_rank = $this->input->post('show_tournament_rank',0);
		$show_weekly_rank = $this->input->post('show_weekly_rank',0);
		
		if(!isset($_POST['id'])){
			$startTime =  convertToTimeStampFromFormat($_POST['start_time']);
			$endTime = convertToTimeStampFromFormat($_POST['end_time']);
			if($startTime == 0 OR $endTime== 0 ){
				echo "Datetime not validated.";exit();
			}
			if($endTime <= time()){
				echo "Endtime not validated.";exit();
			}
			if(! $this->phpvalidator->is_decimal($_POST['entry_fee']) || $_POST['entry_fee'] < 0){
				echo "Entry fee not validated.";exit();
			}
			if(! $this->phpvalidator->is_natural($_POST['free_coins']) || $_POST['free_coins'] < 0){
				echo "Free coins not validated.";exit();
			}
			if(! $this->phpvalidator->is_natural($_POST['number_top_rank']) || $_POST['number_top_rank'] < 0){
				echo "Number of top rank not validated.";exit();
			}
			if(! $this->phpvalidator->is_integer($_POST['limit_coin']) || $_POST['limit_coin'] < -1){
				echo "Limit coins stake not validated.";exit();
			}
			if(! $this->phpvalidator->is_natural($_POST['min_coin']) || $_POST['min_coin'] < 0){
				echo "Minimum coins stake not validated.";exit();
			}
			
			$newId = $this->tournament_entity->createNewTournamentEntity($_POST['name']);
			$TOURNAMENT = $this->tournament_entity->init('id',$newId);
			
		//	$TOURNAMENT->setSportId($_POST['sport_id']); deprecated
			$TOURNAMENT->setStartTime($startTime);
			$TOURNAMENT->setEndTime($endTime);
			$TOURNAMENT->setDescription($_POST['description']);
			$TOURNAMENT->setCreatedDate(time());
			$TOURNAMENT->setEntryFee($_POST['entry_fee']);
			$TOURNAMENT->setFreeCoins($_POST['free_coins']);
			$TOURNAMENT->setPublish( 'publish' );
			$TOURNAMENT->setNumberTopRank($_POST['number_top_rank']);
			$TOURNAMENT->setLimitCoin($_POST['limit_coin']);
			$TOURNAMENT->setMinCoin($_POST['min_coin']);
			$TOURNAMENT->setShowTournamentRank($show_tournament_rank);
			$TOURNAMENT->setShowWeeklyRank($show_weekly_rank);
			
			if($startTime<= time()){
				$TOURNAMENT->setStatus('living');
			}else{
				$TOURNAMENT->setStatus('upcoming');
			}
			$TOURNAMENT->update();
			echo 'ok';
		}else{
			$TOURNAMENT = $this->tournament_entity->init('id',intval($_POST['id']));
			$startTime =  convertToTimeStampFromFormat($_POST['start_time']);
			$endTime = convertToTimeStampFromFormat($_POST['end_time']);
			if($startTime == 0 OR $endTime== 0 ){
				echo "Datetime not validated.";exit();
			}
			if($endTime <= $startTime){
				echo "Endtime not validated.";exit();
			}
			if(! $this->phpvalidator->is_decimal($_POST['entry_fee']) || $_POST['entry_fee'] < 0){
				echo "Entry fee not validated.";exit();
			}
			if(! $this->phpvalidator->is_natural($_POST['free_coins']) || $_POST['free_coins'] < 0){
				echo "Free coins not validated.";exit();
			}
			if(! $this->phpvalidator->is_natural($_POST['number_top_rank']) || $_POST['number_top_rank'] < 0){
				echo "Number of top rank not validated.";exit();
			}
			if(! $this->phpvalidator->is_integer($_POST['limit_coin']) || $_POST['limit_coin'] < -1){
				echo "Limit coins stake not validated.";exit();
			}
			if(! $this->phpvalidator->is_natural($_POST['min_coin']) || $_POST['min_coin'] < 0){
				echo "Minimum coins stake not validated.";exit();
			}
			
		//	$TOURNAMENT->setSportId($_POST['sport_id']);	deprecated
			$TOURNAMENT->setStartTime($startTime);
			$TOURNAMENT->setEndTime($endTime);
			$TOURNAMENT->setDescription($_POST['description']);
			$TOURNAMENT->setName($_POST['name']);
			$TOURNAMENT->setEntryFee($_POST['entry_fee']);
			$TOURNAMENT->setFreeCoins($_POST['free_coins']);
			$TOURNAMENT->setNumberTopRank($_POST['number_top_rank']);
			$TOURNAMENT->setLimitCoin($_POST['limit_coin']);
			$TOURNAMENT->setMinCoin($_POST['min_coin']);
			$TOURNAMENT->setShowTournamentRank($show_tournament_rank);
			$TOURNAMENT->setShowWeeklyRank($show_weekly_rank);
			
			$TOURNAMENT->update();
			echo 'ok';
		}
		$this->session->set_flashdata('success', lang('dataman.success'));
		exit();
	}
	
	function prize_submit(){
		if(!isset($_POST['id'])){
			if(! $this->phpvalidator->is_natural($_POST['rank']) OR $_POST['rank'] <= 0){
				echo "Rank is not valid.";
				exit();
			}
			$prize_id = $this->prize_entity->createNewPrizeEntity($_POST['rank']);
			$PRIZE = $this->prize_entity->init('id', $prize_id);
			$PRIZE->setTournamentId($_POST['tournament_id']);
			$PRIZE->setPrizeName($_POST['prize']);
			$PRIZE->setWinner(0);
			$image = "";
			if(isset($_FILES["image"]) AND !empty($_FILES["image"]['name'])) {
				if(($_FILES["image"]['size']/1000000) > allowMaxFileSize() ){
					$image = '';
				}else{
					$image = $this->module_helper->uploadFile( 
											$_FILES["image"]['tmp_name'],
											$_FILES["image"]['name'],
											$PRIZE->getFolderFileStorage(),
											allowExtensionPictureUpload()
										);
				}	
			}
			$logo = "";
			if(isset($_FILES["logo"]) AND !empty($_FILES["logo"]['name'])) {
				if(($_FILES["logo"]['size']/1000000) > allowMaxFileSize() ){
					$logo = '';
				}else{
					$logo = $this->module_helper->uploadFile( 
											$_FILES["logo"]['tmp_name'],
											$_FILES["logo"]['name'],
											$PRIZE->getFolderFileStorage(),
											allowExtensionPictureUpload()
										);
				}	
			}
			$proof = "";
			if(isset($_FILES["proof"]) AND !empty($_FILES["proof"]['name'])) {
				if(($_FILES["proof"]['size']/1000000) > allowMaxFileSize() ){
					$proof = '';
				}else{
					$proof = $this->module_helper->uploadFile( 
											$_FILES["proof"]['tmp_name'],
											$_FILES["proof"]['name'],
											$PRIZE->getFolderFileStorage(),
											allowExtensionPictureUpload()
										);
				}	
			}
			$PRIZE->setImage($image);
			$PRIZE->setLogo($logo);
			$PRIZE->setValue($_POST['value']);
			$PRIZE->setCourierName($_POST['courier_name']);
			$PRIZE->setShippingDate( convertToTimeStampFromFormat($_POST['shipping_date'], 'Y-m-d') );
			$PRIZE->setTrackingNo($_POST['tracking_no']);
			$PRIZE->setDescription($_POST['description']);
			$PRIZE->setProof($proof);
			$PRIZE->setDeliveryStatus($_POST['delivery_status']);
			$PRIZE->update();
			echo "ok";
		}else{
			if(! $this->phpvalidator->is_natural($_POST['rank']) OR $_POST['rank'] <= 0){
				echo "Rank is not valid.";
				exit();
			}
			$PRIZE = $this->prize_entity->init('id', $_POST['id']);
			$PRIZE->setPrizeName($_POST['prize']);
			$PRIZE->setRank($_POST['rank']);
			
			$image = $PRIZE->getImage();
			if(isset($_FILES["image"]) AND !empty($_FILES["image"]['name'])) {
				if(($_FILES["image"]['size']/1000000) > allowMaxFileSize() ){
					$image = '';
				}else{
					$image = $this->module_helper->uploadFile( 
											$_FILES["image"]['tmp_name'],
											$_FILES["image"]['name'],
											$PRIZE->getFolderFileStorage(),
											allowExtensionPictureUpload()
										);
				}	
			}
			$logo = $PRIZE->getLogo();
			if(isset($_FILES["logo"]) AND !empty($_FILES["logo"]['name'])) {
				if(($_FILES["logo"]['size']/1000000) > allowMaxFileSize() ){
					$logo = '';
				}else{
					$logo = $this->module_helper->uploadFile( 
											$_FILES["logo"]['tmp_name'],
											$_FILES["logo"]['name'],
											$PRIZE->getFolderFileStorage(),
											allowExtensionPictureUpload()
										);
				}	
			}
			$proof = $PRIZE->getProof();
			if(isset($_FILES["proof"]) AND !empty($_FILES["proof"]['name'])) {
				if(($_FILES["proof"]['size']/1000000) > allowMaxFileSize() ){
					$proof = '';
				}else{
					$proof = $this->module_helper->uploadFile( 
											$_FILES["proof"]['tmp_name'],
											$_FILES["proof"]['name'],
											$PRIZE->getFolderFileStorage(),
											allowExtensionPictureUpload()
										);
				}	
			}
			$PRIZE->setLogo($logo);
			$PRIZE->setValue($_POST['value']);
			$PRIZE->setImage($image);
			$PRIZE->setCourierName($_POST['courier_name']);
			$PRIZE->setShippingDate( convertToTimeStampFromFormat($_POST['shipping_date'], 'Y-m-d') );
			$PRIZE->setTrackingNo($_POST['tracking_no']);
			$PRIZE->setDescription($_POST['description']);
			$PRIZE->setProof($proof);
			$PRIZE->setDeliveryStatus($_POST['delivery_status']);
			$PRIZE->update();
			echo "ok";
		}
		$this->session->set_flashdata('success', lang('dataman.success'));
		exit();
	}
	
	function delete_prize(){
		$this->db->where('id', $_POST['id'])->delete(TBL_PRIZE);
		$this->session->set_flashdata('success', lang('dataman.success'));
		echo "ok";
		exit();
	}
	
	function publish_unpublish(){
		$TOURNAMENT = $this->tournament_entity->init('id',$_POST['id']);
		if($TOURNAMENT->getPublish() == 'publish' OR $TOURNAMENT->getPublish() == ""){
			$TOURNAMENT->setPublish('unpublish');
		}else{
			$TOURNAMENT->setPublish('publish');
		}
		$TOURNAMENT->update();
		
		echo 'ok';
		exit();
	}
	
	function tournament_cancel(){
		$TOURNAMENT = $this->tournament_entity->init('id',$_POST['tournament_id']);
		
		$listMatch = $this->match_entity->getArrayListOfMatch($TOURNAMENT->getId());
		
		foreach($listMatch as $match_item){
			$MATCH = $this->match_entity->init('id', $match_item->id);
			
			$listEventLiving = $this->event_entity->getLivingEventOfMatch($match_item->id);
			foreach($listEventLiving as $item){
				$EVENT = $this->event_entity->init('id', $item->id);
				$listBet = $this->bet_entity->getListUserBetEvent($EVENT->getId());
				foreach($listBet as $obj){
					$BET = $this->bet_entity->init('id', $obj->id);
					
					$BET->setStatus('cancelled');
					$BET->setResult('cancelled');
					$BET->update();
					
					$BET->processUserBetResult();
				}
				$EVENT->setStatus('cancelled');
				$EVENT->update();
			}
			
			$livingManualCategories = $this->category_manual_entity->getLivingCategoriesOfMatch($MATCH->getId());
			foreach($livingManualCategories as $cat){
				$CAT_MANUAL = $this->category_manual_entity->init('id', $cat->id);
				$bettingList = $this->bet_manual_entity->getBettingList($CAT_MANUAL->getKeyId());
				foreach($bettingList as $item){
					$BET_MANUAL = $this->bet_manual_entity->init('id',$item->id);
					$BET_MANUAL->setStatus('cancelled');
					$BET_MANUAL->setResult('cancelled');
					$BET_MANUAL->processUserBetResult();
					$BET_MANUAL->update();
				}
				$CAT_MANUAL->setStatus('cancelled');
				$CAT_MANUAL->update();
			}
			
			$MATCH->setStatus('cancelled');
			$MATCH->update();
		}
		
		$livingEventsOfTournamentPredicts = $this->event_tournament_entity->getLivingEventOfTournament($TOURNAMENT->getId());
		foreach($livingEventsOfTournamentPredicts as $item){
			$EVENT = $this->event_tournament_entity->init('id',$item->id);
			$listBet = $this->bet_tournament_entity->getListUserBetEvent($EVENT->getId());
			foreach($listBet as $obj){
				$BET = $this->bet_tournament_entity->init('id', $obj->id);
				
				$BET->setStatus('cancelled');
				$BET->setResult('cancelled');
				$BET->update();
				
				$BET->processUserBetResult();
			}
			$EVENT->setStatus('cancelled');
			$EVENT->update();
		}
		
		$livingManualCategories = $this->category_manual_tournament_entity->getLivingCategoriesOfMatch($TOURNAMENT->getId());
		foreach($livingManualCategories as $cat){
			$CAT_MANUAL = $this->category_manual_tournament_entity->init('id', $cat->id);
			$bettingList = $this->bet_manual_tournament_entity->getBettingList($CAT_MANUAL->getKeyId());
			foreach($bettingList as $item){
				$BET_MANUAL = $this->bet_manual_tournament_entity->init('id',$item->id);
				$BET_MANUAL->setStatus('cancelled');
				$BET_MANUAL->setResult('cancelled');
				$BET_MANUAL->processUserBetResult();
				$BET_MANUAL->update();
			}
			$CAT_MANUAL->setStatus('cancelled');
			$CAT_MANUAL->update();
		}
		
		$TOURNAMENT->setStatus('cancelled');
		$TOURNAMENT->update();
		$this->session->set_flashdata('success', lang('dataman.success'));
		
		echo 'ok';
		exit();
	}
	
	function tournament_finish(){
		$tournament_id = intval($_POST['tournament_id']);
		$TOURNAMENT = $this->tournament_entity->init('id', $tournament_id);
		 
		$canFinishTournamentBet = true;
		$livingEventsOfTournamentPredicts = $this->event_tournament_entity->getLivingEventOfTournament($TOURNAMENT->getId());
		foreach($livingEventsOfTournamentPredicts as $item){
			$EVENT = $this->event_tournament_entity->init('id',$item->id);
			if( $EVENT->getResult() == '' ){
				$canFinishTournamentBet = false;
				break;
			}
		}
		if( !$canFinishTournamentBet ){
			echo "Required set result of event tournament prediction firstly.";exit();
		}
		
		$canFinishManualEvent = true;
		$livingManualCategories = $this->category_manual_tournament_entity->getLivingCategoriesOfMatch($TOURNAMENT->getId());
		foreach($livingManualCategories as $cat){
			$CAT_MANUAL = $this->category_manual_tournament_entity->init('id', $cat->id);
			if($this->bet_manual_tournament_entity->isBettingStatusCategory($CAT_MANUAL->getKeyId())){
				$canFinishManualEvent = false;
				break;
			}
		}
		
		if(!$canFinishManualEvent){
			echo "Please set result of manual tournament before.";exit();
		}
			
		
		$living_match_array_of_tournament = $this->match_entity->getMatchOfTournamentByStatus($tournament_id, $status="living");
		foreach($living_match_array_of_tournament as $item){
			$MATCH = $this->match_entity->init('id',$item->id);
			 
			$canFinish = true;
			$eventArray = $this->event_entity->getLivingEventOfMatch($MATCH->getId());
			foreach($eventArray as $item){
				$EVENT = $this->event_entity->init('id',$item->id);
				if( $EVENT->getResult() == '' ){
					$canFinish = false;
					break;
				}
			}
			if( !$canFinish ){
				echo "Required set result of event firstly.";exit();
			}
			
			$canFinishManualEvent = true;
			$livingManualCategories = $this->category_manual_entity->getLivingCategoriesOfMatch($MATCH->getId());
			foreach($livingManualCategories as $cat){
				$CAT_MANUAL = $this->category_manual_entity->init('id', $cat->id);
				if($this->bet_manual_entity->isBettingStatusCategory($CAT_MANUAL->getKeyId())){
					$canFinishManualEvent = false;
					break;
				}
			}
			
			if(!$canFinishManualEvent){
				echo "Please set result of manual events before.";exit();
			}
			
			
			foreach($livingManualCategories as $cat){
				$CAT_MANUAL = $this->category_manual_entity->init('id', $cat->id);
				$bettingList = $this->bet_manual_entity->getBettingList($CAT_MANUAL->getKeyId());
				foreach($bettingList as $item){
					$BET_MANUAL = $this->bet_manual_entity->init('id',$item->id);
					$BET_MANUAL->setStatus('finished');
					$BET_MANUAL->processUserBetResult();
					$BET_MANUAL->update();
				}
				$CAT_MANUAL->setStatus('closed');
				$CAT_MANUAL->update();
			}
		
			$betArray = $this->bet_entity->getBetListOfMatch($MATCH->getId());
			foreach($betArray as $obj){
				$EVENT = $this->event_entity->init('id',$obj->event_id);
				$BET = $this->bet_entity->init('id', $obj->id);
				$BET->setStatus('finished');
				$BET->setResult($EVENT->getResult());
				$BET->update();
				$BET->processUserBetResult();
			}
			
			$eventArray = $this->event_entity->getLivingEventOfMatch($MATCH->getId());
			foreach($eventArray as $item){
				$EVENT = $this->event_entity->init('id',$item->id);
				$EVENT->setStatus('closed');
				$EVENT->update();
			}
			$MATCH->setStatus('closed');
			$MATCH->update();
		}
		
		$livingEventsOfTournamentPredicts = $this->event_tournament_entity->getLivingEventOfTournament($TOURNAMENT->getId());
		foreach($livingEventsOfTournamentPredicts as $item){
			$EVENT = $this->event_tournament_entity->init('id',$item->id);
			$listBet = $this->bet_tournament_entity->getListUserBetEvent($EVENT->getId());
			foreach($listBet as $obj){
				$BET = $this->bet_tournament_entity->init('id', $obj->id);
				
				$BET->setStatus('finished');
				$BET->setResult($EVENT->getResult());
				$BET->update();
				
				$BET->processUserBetResult();
			}
			$EVENT->setStatus('closed');
			$EVENT->update();
		}
		
		
		$livingManualCategories = $this->category_manual_tournament_entity->getLivingCategoriesOfMatch($TOURNAMENT->getId());
		foreach($livingManualCategories as $cat){
			$CAT_MANUAL = $this->category_manual_tournament_entity->init('id', $cat->id);
			$bettingList = $this->bet_manual_tournament_entity->getBettingList($CAT_MANUAL->getKeyId());
			foreach($bettingList as $item){
				$BET_MANUAL = $this->bet_manual_tournament_entity->init('id',$item->id);
				$BET_MANUAL->setStatus('finished');
				$BET_MANUAL->processUserBetResult();
				$BET_MANUAL->update();
			}
			$CAT_MANUAL->setStatus('closed');
			$CAT_MANUAL->update();
		}
		
		$TOURNAMENT->setStatus('closed');
		$TOURNAMENT->setIsFinish('yes');
		$TOURNAMENT->update();
		$this->email_sender->_sendEmailToUsers_notifyTournamentFinished($tournament_id);
		$this->session->set_flashdata('success', lang('dataman.success'));
		
		echo 'ok';
		exit();
	}	
	
	
	// end class
}
